package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2023-01-28
 */
@RestController
@RequestMapping("/eduorder/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 生成订单
     * @param courseId
     * @param request
     * @return
     */
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request){
        String id = JwtUtils.getMemberIdByJwtToken(request);
        //创建订单返回订单号
        String orderNo=orderService.createOrders(courseId,id);
        return R.ok().data("orderNo",orderNo);
    }

    /**
     * 回显订单
     * @param orderId
     * @return
     */
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId){
        LambdaQueryWrapper<Order> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getOrderNo,orderId);
        Order one = orderService.getOne(queryWrapper);
        return R.ok().data("item",one);
    }

    /**
     * 根据课程id和用户id查询订单状态
     * @param courseId
     * @param request
     * @return
     */
    @GetMapping("idBuyCourse/{courseId}")
    public R getStatus(@PathVariable String courseId,HttpServletRequest request){

        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);

        LambdaQueryWrapper<Order> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getCourseId,courseId);
        queryWrapper.eq(Order::getMemberId,memberIdByJwtToken);
        queryWrapper.eq(Order::getStatus,1);
        int count = orderService.count(queryWrapper);
        return R.ok().data("status",count>0);
    }
}

